package com.example.lsrsbackend.controller;

import com.example.lsrsbackend.model.DTO.ReservationRequest;
import com.example.lsrsbackend.model.Seat;
import com.example.lsrsbackend.model.view.ReservationVO;
import com.example.lsrsbackend.service.ReservationService;
import com.example.lsrsbackend.service.SeatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.lsrsbackend.model.view.SeatVO;

import java.util.List;

@RestController
@RequestMapping("/api/seat")
@Slf4j
public class SeatController {

    @Autowired
    private SeatService seatService;

    @Autowired
    private ReservationService reservationService;

    // 获取所有座位信息，包括状态：力求在前端展示不同状态 -- 每一层每一个
    @GetMapping("/status")
    public ResponseEntity<List<Seat>> getAllSeatStatus() {
        try {
            List<Seat> seats = seatService.getAllSeatStatus();
            return ResponseEntity.ok(seats);
        } catch (Exception e) {

            log.error("获取座位状态失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    // 获取特定区域座位：某一层的座位
    @GetMapping("/area/{area}")
    public ResponseEntity<List<Seat>> getSeatsByArea(@PathVariable String area) {
        try {
            List<Seat> seats = seatService.getSeatsByArea(area);
            return ResponseEntity.ok(seats);
        } catch (Exception e) {
            log.error("获取区域座位失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    //TODO 新增座位
    @PostMapping("/add")
    public ResponseEntity<Seat> addSeat(@RequestBody Seat seat) {
        try {
            // 参数验证
            if (seat.getSeatNumber() == null || seat.getFloorAreaId() == null) {
                return ResponseEntity.badRequest().build();
            }

            Seat savedSeat = seatService.addSeat(seat);
            return ResponseEntity.ok(savedSeat);
        } catch (Exception e) {
            log.error("新增座位失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    //TODO 更新座位
    @PatchMapping("/{seatId}")
    public ResponseEntity<Seat> updateSeat(@PathVariable Long seatId, @RequestBody Seat seat) {
        try {
            // 参数验证
            if (seat.getSeatNumber() == null || seat.getFloorAreaId() == null) {
                return ResponseEntity.badRequest().build();
            }

            Seat updatedSeat = seatService.updateSeat(seatId, seat);
            return ResponseEntity.ok(updatedSeat);
        } catch (Exception e) {
            log.error("更新座位失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
    // TODO 删除座位
    @DeleteMapping("/{seatId}")
    public ResponseEntity<String> deleteSeat(@PathVariable Long seatId) {
        try {
            seatService.deleteSeat(seatId);
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            log.error("删除座位失败", e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // TODO 预约座位：  前端json --> （1）在预约记录里记录数据（2）修改座位状态
    @PostMapping("/reserve")
    public ResponseEntity<String> reserveSeat(@RequestBody ReservationRequest request) {
        try {
            // 参数验证
            if (request.getSeatId() == null || request.getUsername() == null) {
                return ResponseEntity.badRequest().body("座位ID和用户名不能为空");
            }

            // 检查用户状态
            if (reservationService.isUserFrozen(request.getUsername())) {
                return ResponseEntity.badRequest().body("用户被冻结，不可以预约");
            }

            String reservationId = reservationService.reserveSeat(request);
            return ResponseEntity.ok(reservationId);
        } catch (Exception e) {
            // 所有业务异常现在都是 RuntimeException，统一在这里处理
            log.warn("预约座位失败", e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // TODO 取消预约：   删除预约记录
    @PostMapping("/reservation/{reservationId}/cancel")
    public ResponseEntity<String> cancelReservation(
            @PathVariable String reservationId,
            @RequestHeader(value = "username", required = false) String username) {
        try {
            // 参数验证
            if (reservationId == null) {
                return ResponseEntity.badRequest().body("预约ID不能为空");
            }


            // 如果username为空，则不检查用户权限
            if (username == null || username.trim().isEmpty()) {
                reservationService.cancelReservationWithoutUserCheck(reservationId);
            } else {
                reservationService.cancelReservation(reservationId, username);
            }
            return ResponseEntity.ok("取消成功");
        } catch (Exception e) {
            log.warn("取消预约失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // TODO  签到：   记录签到时间到预约记录
    @PostMapping("/reservation/{reservationId}/checkin")
    public ResponseEntity<String> checkIn(
            @PathVariable String reservationId,
            @RequestHeader("username") String username) {
        try {
            System.out.println(reservationId + " " + username);
            // 参数验证
            if (reservationId == null || username == null) {
                return ResponseEntity.badRequest().body("预约ID和用户名不能为空");
            }

            reservationService.checkIn(reservationId, username);
            return ResponseEntity.ok("签到成功");
        } catch (Exception e) {
            log.warn("签到失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //TODO 用户暂离：暂离座位
    @PostMapping("/reservation/{reservationId}/away")
    public ResponseEntity<String> temporaryLeave(
            @PathVariable String reservationId,
            @RequestHeader("username") String username) {
        try {

            System.out.println(reservationId + " " + username);
            // 参数验证
            if (reservationId == null || username == null) {
                return ResponseEntity.badRequest().body("预约ID和用户名不能为空");
            }

            reservationService.temporaryLeave(reservationId, username);
            return ResponseEntity.ok("暂离成功");
        } catch (Exception e) {
            log.warn("暂离失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //TODO 用户从暂离返回
    @PostMapping("/reservation/{reservationId}/return")
    public ResponseEntity<String> returnFromLeave(
            @PathVariable String reservationId,
            @RequestHeader("username") String username) {
        try {
            // 参数验证
            if (reservationId == null || username == null) {
                return ResponseEntity.badRequest().body("预约ID和用户名不能为空");
            }

            reservationService.returnFromLeave(reservationId, username);
            return ResponseEntity.ok("返回成功");
        } catch (Exception e) {
            log.warn("返回失败: {}", e.getMessage());
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // TODO 获取用户预约记录：获取预约列表
    @GetMapping("/reservations")
    public ResponseEntity<List<ReservationVO>> getUserReservations(
            @RequestHeader("username") String username,
            @RequestParam(defaultValue = "7") int days) {
        try {
            // 参数验证
            if (username == null) {
                return ResponseEntity.badRequest().build();
            }

            List<ReservationVO> reservations = reservationService.getUserReservations(username, days);
            return ResponseEntity.ok(reservations);
        } catch (Exception e) {
            log.error("获取预约记录失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    //新增：获取座位详情
    @GetMapping("/{seatId}")
    public ResponseEntity<SeatVO> getSeatDetail(@PathVariable String seatId) {
        try {
            // 参数验证
            if (seatId == null) {
                return ResponseEntity.badRequest().build();
            }

            SeatVO seat = seatService.getSeatDetail(seatId);
            return ResponseEntity.ok(seat);
        } catch (Exception e) {
            log.warn("获取座位详情失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
}